Session-Based Authentication (PHP)
This guide covers secure, persistent authentication across app sessions for Giftme MiniStores using PHP, cookies, and the JS bridge.
1. Set a Secure Cookie from PHP (after login)
In your login controller (e.g., POST /login), after verifying user credentials:
<?php
$sessionToken = generateSessionToken($userId); // your logic
setcookie(
'giftme_session',
$sessionToken,
[
'expires' => strtotime('+30 days'),
'path' => '/',
'domain' => '.example.com', // subdomain-safe
'secure' => true, // HTTPS only
'httponly' => true, // Inaccessible to JS
'samesite' => 'Lax' // Allows top-level GETs
]
);
header('Content-Type: application/json');
echo json_encode(['success' => true]);
2. Middleware: Detect Cookie and Inject JS Variable
In your layout or page controller:
<?php
$sessionValid = isset($_COOKIE['giftme_session']) &&
isValid($_COOKIE['giftme_session']);
Inject into HTML:
<script>
window.giftmeHasSession = <?= $sessionValid ? 'true' : 'false' ?>;
</script>
3. Frontend: Call JS Bridge Only If Needed
if (!window.giftmeHasSession) {
await giftmeGetAuthCode({ miniStoreId: 'ABC123' });
}
4. If Using fetch() to Log In (SPA or JS login)
Backend Headers:
<?php
header('Access-Control-Allow-Origin: https://mini.example.com');
header('Access-Control-Allow-Credentials: true');
Frontend Fetch:
const res = await fetch('https://auth.example.com/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
Summary
| Step | Action |
|---|---|
| Set Cookie | Use setcookie('giftme_session', ...) securely |
| Detect Session | Check $_COOKIE['giftme_session'] in PHP |
| Expose to JS | Inject window.giftmeHasSession = true/false |
| Call JS Bridge | Only if window.giftmeHasSession === false |
| SPA Login | Use fetch(..., credentials: 'include') and proper CORS headers |